package com.shuai.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuai.common.constant.ChatType;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.user.domain.entity.User;
import com.shuai.user.domain.entity.UserSession;
import com.shuai.user.service.UserSessionService;
import com.shuai.user.mapper.UserSessionMapper;
import org.apache.commons.lang3.CharSequenceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author bxs
 * @description 针对表【user_session】的数据库操作Service实现
 * @createDate 2024-07-04 13:19:29
 */
@Service
public class UserSessionServiceImpl extends ServiceImpl<UserSessionMapper, UserSession>
        implements UserSessionService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<UserSession> listUserSession(String userId, ChatType chatType) {
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId);
        if (StringUtils.isBlank(userJson)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未获取到用户身份信息");
        }
        User user = JSONUtil.toBean(userJson, User.class);
        LambdaQueryWrapper<UserSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserSession::getUserId, user.getId());
        queryWrapper.eq(UserSession::getType, chatType.getCode());
        queryWrapper.orderByDesc(UserSession::getUpdateTime);
        return this.list(queryWrapper);
    }
}




